package com.yzh.openai.types.utils.xml;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.apache.commons.lang3.StringUtils;

import java.io.Writer;

public class XmlUtil {
    /**
     * bean转xml时加上![CDATA[]]，微信要求
     */
    public static XStream getMyXStream() {
        return new XStream(new XppDriver() {
            @Override
            public HierarchicalStreamWriter createWriter(Writer out) {
                return new PrettyPrintWriter(out) {
                    @Override
                    public void startNode(String name, Class clazz) {
                        super.startNode(name, clazz);
                    }

                    @Override
                    protected void writeText(QuickWriter writer, String text) {
                        //不是数字就加入前后缀
                        if (!StringUtils.isNumeric(text)) {
                            writer.write("<![CDATA[");
                            writer.write(text);
                            writer.write("]]>");
                        } else {
                            writer.write(text);
                        }
                    }
                };
            }
        });
    }

    /**
     * bean转成微信的xml格式
     */
    public static String beanToXml(Object object) {
        XStream xStream = getMyXStream();
        //设置XML根节点名称为xml
        xStream.alias("xml", object.getClass());
        //将Java对象的注解转换为xml中的标签
        xStream.processAnnotations(object.getClass());
        //转为xml格式字符串
        String xml = xStream.toXML(object);
        if (!StringUtils.isEmpty(xml)) {
            return xml;
        }else {
            return null;
        }
    }

    /**
     * xml转为bean
     */
    public static <T> T xmlToBean(String xml, Class clazz) {
        XStream stream = new XStream(new DomDriver());
        //设置默认安全模式，避免安全问题
        XStream.setupDefaultSecurity(stream);
        //允许解析指定类的实例
        stream.allowTypes(new Class[]{clazz});
        //处理指定类的注解
        stream.processAnnotations(new Class[]{clazz});
        //设置为不引用模式，避免生成xml的引用
        stream.setMode(XStream.NO_REFERENCES);
        //设置别名
        stream.alias("xml", clazz);
        return (T) stream.fromXML(xml);
    }
}
